{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成器函数，函数里只要有yield关键字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gen_func():\n",
    "    yield 1\n",
    "    yield 2\n",
    "    yield 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "# 生成器对象，python编译字节码的时候就产生了，\n",
    "gen = gen_func()\n",
    "for i in gen:\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 情性求值，延迟求值提供了可能\n",
    "def gen_fib(idx):\n",
    "    n, a, b = 0, 0, 1\n",
    "    while n < idx:\n",
    "        yield b\n",
    "        a, b = b, a + b\n",
    "        n += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "1\n",
      "2\n",
      "3\n",
      "5\n",
      "8\n",
      "13\n",
      "21\n",
      "34\n",
      "55\n"
     ]
    }
   ],
   "source": [
    "for i in gen_fib(10):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "def gen_f1():\n",
    "    for i in range(10):\n",
    "        yield i\n",
    "\n",
    "def gen_f2():\n",
    "    for i in gen_f1():\n",
    "        yield i + 1\n",
    "        return 2\n",
    "\n",
    "for i in gen_f2():\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gen_r1():\n",
    "    for i in range(10):\n",
    "        if i > -1:\n",
    "            return i\n",
    "        yield i\n",
    "        # # 被调用后执行\n",
    "        # print(\"end\")\n",
    "\n",
    "for i in gen_r1():\n",
    "    print(i)\n",
    "    pass\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "jupter-env-10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
